// Content script for QKL Wallet Extension
class WalletContentScript {
  private isInjected: boolean = false;

  constructor() {
    this.setupMessageHandlers();
    this.injectWalletProvider();
  }

  private setupMessageHandlers(): void {
    // 监听来自页面的消息
    window.addEventListener('message', (event) => {
      if (event.source !== window) return;
      
      if (event.data.type === 'QKL_WALLET_REQUEST') {
        this.handleWalletRequest(event.data);
      }
    });
  }

  private injectWalletProvider(): void {
    if (this.isInjected) return;
    
    // 注入QKL钱包提供者到页面
    const script = document.createElement('script');
    script.textContent = `
      (function() {
        if (window.qklWallet) return;
        
        window.qklWallet = {
          isQKLWallet: true,
          version: '1.0.0',
          
          // 请求账户
          request: async (method, params = []) => {
            return new Promise((resolve, reject) => {
              const requestId = Date.now() + Math.random();
              
              // 发送请求到扩展
              window.postMessage({
                type: 'QKL_WALLET_REQUEST',
                id: requestId,
                method: method,
                params: params
              }, '*');
              
              // 监听响应
              const handleResponse = (event) => {
                if (event.data.type === 'QKL_WALLET_RESPONSE' && 
                    event.data.id === requestId) {
                  window.removeEventListener('message', handleResponse);
                  
                  if (event.data.error) {
                    reject(new Error(event.data.error));
                  } else {
                    resolve(event.data.result);
                  }
                }
              };
              
              window.addEventListener('message', handleResponse);
              
              // 超时处理
              setTimeout(() => {
                window.removeEventListener('message', handleResponse);
                reject(new Error('请求超时'));
              }, 30000);
            });
          },
          
          // 便捷方法
          requestAccounts: () => window.qklWallet.request('eth_requestAccounts'),
          getAccounts: () => window.qklWallet.request('eth_accounts'),
          sendTransaction: (tx) => window.qklWallet.request('eth_sendTransaction', [tx]),
          signMessage: (message) => window.qklWallet.request('personal_sign', [message]),
          signTypedData: (typedData) => window.qklWallet.request('eth_signTypedData', [typedData]),
          switchChain: (chainId) => window.qklWallet.request('wallet_switchEthereumChain', [{ chainId }]),
          addChain: (chainParams) => window.qklWallet.request('wallet_addEthereumChain', [chainParams])
        };
        
        // 兼容MetaMask API
        if (window.ethereum) {
          window.ethereum.isQKLWallet = true;
          window.ethereum.qklWallet = window.qklWallet;
        } else {
          window.ethereum = window.qklWallet;
        }
        
        // 触发连接事件
        window.dispatchEvent(new Event('ethereum#initialized'));
      })();
    `;
    
    document.documentElement.appendChild(script);
    script.remove();
    this.isInjected = true;
  }

  private async handleWalletRequest(data: any): Promise<void> {
    try {
      const response = await chrome.runtime.sendMessage({
        type: 'DAPP_REQUEST',
        data: {
          origin: window.location.origin,
          method: data.method,
          params: data.params
        }
      });

      // 发送响应回页面
      window.postMessage({
        type: 'QKL_WALLET_RESPONSE',
        id: data.id,
        result: response.data,
        error: response.error
      }, '*');
    } catch (error) {
      window.postMessage({
        type: 'QKL_WALLET_RESPONSE',
        id: data.id,
        error: error.message
      }, '*');
    }
  }
}

// 初始化内容脚本
new WalletContentScript();
